$NG.AllReady(function (page, { useAction, useBeforeClick, useValuesChange, useClick, useUpdateRow, subscribe, useUpdateRows }) {
    const mstform = $NG.getCmpApi("p_form_fbsqrtz_m")
    const dgrid1 = $NG.getCmpApi("p_form_fbsqrtz_d1")
    const getHeadValue = (str)=>mstform.getItem(str).getValue()

    if(page.oType == 'add'){
        mstform.getItem("u_fbfmc").setValue({
            label:$NG.getUser().orgName,
            value:$NG.getUser().orgID
        })
    }

    useValuesChange(()=>{
         getFbchInFblxInfoByPhid()
    },"p_form_fbsqrtz_m.u_fbxmchsbh")

    useValuesChange(()=>{
        getSupplyInfo()
    },"p_form_fbsqrtz_m.u_jfdw")

    useClick(()=>{
        getFileId()
    },"u_xzdrmb")
    function getFbchInFblxInfoByPhid(){
        const phid = getHeadValue("u_fbxmchsbh")
        if(!phid) return 
        $NG.execServer("getFblxInfoByChPhid",{phid},(res)=>{
            if(res.count == 0) return 
            const datas = JSON.parse(res.data)[0].extendObjects
            $NG.updateState((updater)=>{
                updater.data.p_form_fbsqrtz_m.setProps({
                    u_xmblb:datas.xmblb,
                    u_fbxmmc:datas.fbxmmc,
                    u_fbxmlb:{
                        label:datas.fbxmlb_name,
                        value:datas.fbxmlb_phid
                    },
                    u_jkjsfs:datas.jkjsfs,
                    u_ncydzbfs:{
                        label:datas.ncydzbfs_name,
                        value:datas.ncydzbfs_phid
                    },
                    u_lxsqbh:{
                        label:datas.lxbh,
                        value:datas.phid
                    },
                    phid_pc:{
                        label:datas.phid_pc,
                        value:datas.phid_pc_exname
                    },
                    u_yjfbzje:datas.yjfbzje,
                    u_sfjyzhjlspty:{
                        label:datas.sfty_name,
                        value:datas.sfty_phid
                    }
                })
            })
        })
    }

    async function getSupplyInfo(){
        const phid = getHeadValue("u_jfdw")
        if(!phid) return 
        const res = await $NG.execServer("getSupplyInfo",{phid})
        if(res.count == 0) return 
        const datas = JSON.parse(res.data)[0].extendObjects
        console.log(`datas`,datas);
        const arr = [
            {
                key:"u_fbszzdj",
                value:datas.user_zzdj
            },
            {
                key:"u_fbsxcfzr",
                value:datas.user_fbsxcfzr
            },
            {
                key:"u_fbsxcfzrsfzh",
                value:datas.user_fbsxcfzrsfz
            },
            {
                key:"u_fbsxcfzrlxdh",
                value:datas.user_fbsxcfzrlxdh
            }
        ]
        setHeadValues(arr)
    }

    // 查询附件，找到附件的数量
    async function getFileId() {
        let asr = null
        await $NG.execServer("getAttachmentByasr", { code: '138657ed-7fa1-4921-ba12-c602c80df321' }, (res) => {
            if (res.count == 0) {
                asr = null
            } else {
                asr = JSON.parse(res.data)[0].extendObjects
            }
        })
        if (!asr) {
            $NG.alert("没有模板可以下载！")
            return
        }
        const origin = location.origin;
        const router = "/JFileSrv/reactAttach/download";
        const param = {
            asrFid: asr.asr_fid,
            asrName: asr.asr_name,
            busTypeCode: "drmb",
            loginId: "6870000000000016",
            orgId: "1",
            asrFilldt: asr.asr_filldt
        };

        const query = new URLSearchParams(param).toString();
        const url = `${origin}${router}?${query}`;

        try {
            // 1. fetch 请求，加上你需要的 header
            const res = await fetch(url, {
                method: "GET",
                headers: {
                    "Authorization": localStorage.getItem("Auth$#$i8$#$6.3sp1$#$lsz"),
                    "dbtoken": "0001", // 🔴 在这里加请求
                }
            });

            if (!res.ok) {
                throw new Error("下载失败: " + res.status);
            }
            // 从响应头解析文件名
            const disposition = res.headers.get("Content-Disposition");
            let filename = asr.asr_name
            if (disposition && disposition.includes("filename=")) {
                const match = disposition.match(/filename="?([^"]+)"?/);
                if (match.length > 1) {
                    filename = decodeURIComponent(match[1]);
                }
            }
            // 转 blob
            const blob = await res.blob();

            // 创建临时链接并下载
            const link = document.createElement("a");
            link.href = URL.createObjectURL(blob);
            link.download = filename; // ✅ 指定文件名
            link.target = "_blank";
            document.body.appendChild(link);
            link.click();
            link.remove();

            setTimeout(() => URL.revokeObjectURL(link.href), 60000);
        } catch (err) {
            console.error(err);
            $NG.alert("下载出错啦！");
        }
        // const button = document.createElement('a');
        // button.style.display = 'none'
        // button.href = url
        // document.body.appendChild(button);
        // button.click()

    }

     // 表头批量赋值
    function setHeadValues(arr) {
        arr.forEach(item => {
            console.log(`执行更新`, item);
            mstform.getItem(item.key)?.setValue(item.value)
        })
    }
})